#! /usr/bin/env python3

import os
import re

usertool = "./dpdk-devbind.py"
# nic_cards = ["\"Virtio network device 1000\"","\"82599ES 10-Gigabit SFI/SFP+ Network Connection 10fb\""]
nic_cards = ["\"82599ES 10-Gigabit SFI/SFP+ Network Connection 10fb\""]
controller_addr = "10.112.132.216:6633"

def scan_nic_cards():
    pcino = []
    nicname = []
    nic_types = []
    for nic_card in nic_cards:
        command_1 = usertool + " --status | grep " + nic_card
        results = os.popen(command_1).readlines()
        for result in results:        
            pci = re.search(r'([0-9]|[a-f]){4}:([0-9]|[a-f]){2}:([0-9]|[a-f]){2}.([0-9]|[a-f])', result)
            name = re.search(r'ens[0-9]+', result)
            if pci != None:
                pcino.append(pci.group())
            if name != None:
                nicname.append(name.group())

            if(nic_card == "\"Virtio network device 1000\""):
                nic_types.append("virtio")
            else:
                nic_types.append("ixgbe")
    return  pcino, nicname, nic_types


def ovs_config():
    print("===Welcome to DPDK Config Script===")

    print("===================================")
    print("Step 0: Check root user")
    results = os.popen("whoami").readlines()
    if (len(results) == 0) | (results[0] != "root\n"):
        print("Not a root user, bye!")
        return

    print("===================================")
    print("Step 1: Scan all nic cards.")
    pcino, nicname, nic_types = scan_nic_cards()
        
    print("pci no: " + str(pcino))
    print("dev name (using kernel): " + str(nicname))

    print("===================================")
    print("Step 2: Config ovs.")
    commands = "ovs-vsctl del-br br0\n" \
             + "ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev\n"
             
    # os.popen("ovs-vsctl del-br br0\n")
    # os.popen("ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev")
    i=1
    for pci, nic_type in zip(pcino, nic_types):
        print(pci)
        rx_mq_mode="false" if nic_type == "virtio" else "true"
        commands += "ovs-vsctl add-port br0 dpdk" + str(i) +" -- set Interface dpdk" + str(i) + " type=dpdk ofport_request=" + str(i) +" options:dpdk-devargs=" + pci + " options:rx_mq_mode="+rx_mq_mode + " options:speeds=auto\n"
        # os.popen("ovs-vsctl add-port br0 dpdk" + str(i) +" -- set Interface dpdk" + str(i) + " type=dpdk ofport_request=" + str(i) +" options:dpdk-devargs=" + pci + " options:rx_mq_mode="+rx_mq_mode + " options:speeds=1G")
        i = i+1
    commands += 'ovs-vsctl set-controller br0 tcp:'+ controller_addr+'\n'
    commands += 'ovs-vsctl set bridge br0 fail_mode=secure'+'\n'
    os.popen(commands)

if __name__ == "__main__":
    ovs_config()
